//
//  YYT_MVViewViewController.m
//  AudioVisualFeast
//
//  Created by 张琪 on 16/1/28.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "YYT_MVViewViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface YYT_MVViewViewController ()
@property (nonatomic, retain) AVPlayer *player;
@property (nonatomic, retain) AVPlayerLayer *playerLayer;
//控制台view
@property (nonatomic, retain) UIView *controlAV;
//控制台显示持续时间
@property (nonatomic, assign) NSInteger secondsAV;
//topview
@property (nonatomic, retain) UILabel *topview;
//left声音view
@property (nonatomic, retain) UIView *leftview;
//音量初始
@property (nonatomic, assign) float soundone;
//right亮度view
@property (nonatomic, retain) UIView *rightview;
//开始暂停
@property (nonatomic, retain) UIButton *startstop;

//进度条
@property (nonatomic, retain) UISlider *jindu;
@property (nonatomic, retain) NSTimer *timer;
//时间
@property (nonatomic, assign) NSInteger fen;
@property (nonatomic, assign) NSInteger miao;
@property (nonatomic, retain) UILabel *times;
@property (nonatomic, retain) UIButton *fullScreen;

@property (nonatomic, retain) AVPlayerItem *playerItem;
@property (nonatomic, retain) UIView *huancun;
//音量
@property (nonatomic, retain) UILabel *yinliang;
//亮度
@property (nonatomic, retain) UIView *liangdu;
@property (nonatomic, retain) UILabel *liangdula;

@property (nonatomic, assign) NSInteger full;
@end

static YYT_MVViewViewController *danli = nil;
//定义全局变量

@implementation YYT_MVViewViewController

+(instancetype)shareLYKMVPlayerViewController {
    
    //    在多线程中保证只初始化一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        danli = [[YYT_MVViewViewController alloc] init];
        
    });
    return danli;
}
- (void)loadView {
    [super loadView];
    
}

-(void)creatav {
    self.full = 0;
    NSURL *sourceMovieURL = [NSURL URLWithString:self.url];
    AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:sourceMovieURL options:nil];
    self.playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playerLayer.frame = CGRectMake(0, 0, self.view.layer.bounds.size.height, self.view.layer.bounds.size.width);
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    [self.view.layer addSublayer:self.playerLayer];
}
-(void)aaaa {
    [self.playerLayer removeFromSuperlayer];
    NSURL *sourceMovieURL = [NSURL URLWithString:self.url];
    AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:sourceMovieURL options:nil];
    self.playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playerLayer.frame = CGRectMake(0, 0, self.view.layer.bounds.size.height, self.view.layer.bounds.size.width);
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    NSInteger num = self.now;
    CMTime dragedCMTime = CMTimeMake(num, 1);
    [self.player seekToTime:dragedCMTime];
    if (self.startstopnum != 1) {
        [self.player play];
    } else if (self.startstopnum == 1) {
        [self.player pause];
    }
    [self.view.layer addSublayer:self.playerLayer];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timers) userInfo:nil repeats:YES];
    self.player.volume = 0;
    
    [self.topview removeFromSuperview];
    [self.leftview removeFromSuperview];
    [self.rightview removeFromSuperview];
    [self.controlAV removeFromSuperview];
    [self controlAVview];
}

- (NSTimeInterval)availableDuration {
    NSArray *loadedTimeRanges = [[self.player currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result = startSeconds + durationSeconds;// 计算缓冲总进度
    return result;
}


//视频控制台
-(void)controlAVview {
    self.liangdu = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.height, self.view.bounds.size.width)];
    self.liangdu.alpha = 0;
    self.liangdu.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.liangdu];
    
    //    topview
    self.topview = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.layer.bounds.size.height, 30)];
    self.topview.text = self.titleNames;
    self.topview.font = [UIFont systemFontOfSize:15];
    self.topview.textColor = [UIColor whiteColor];
    self.topview.alpha = 0.0;
    self.topview.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.topview];
    
    //    leftview
    self.leftview = [[UIView alloc] initWithFrame:CGRectMake(0, 30, self.view.layer.bounds.size.height / 2, self.view.layer.bounds.size.width - 60)];
    [self.view addSubview:self.leftview];
    self.yinliang = [[UILabel alloc] initWithFrame:CGRectMake(20, 60, 90, 20)];
    self.yinliang.textColor = [UIColor whiteColor];
    self.yinliang.font = [UIFont systemFontOfSize:13];
    [self.leftview addSubview:self.yinliang];
    
    self.yinliang.hidden = YES;
    
    //    rightview
    self.rightview = [[UIView alloc] initWithFrame:CGRectMake(self.view.layer.bounds.size.height / 2, 30, self.view.layer.bounds.size.height / 2, self.view.layer.bounds.size.width - 60)];
    [self.view addSubview:self.rightview];
    self.liangdula = [[UILabel alloc] initWithFrame:CGRectMake(self.rightview.bounds.size.width - 110, 60, 90, 20)];
    self.liangdula.textColor = [UIColor whiteColor];
    self.liangdula.font = [UIFont systemFontOfSize:13];
    [self.rightview addSubview:self.liangdula];
    
    self.liangdula.hidden = YES;
    
    UITapGestureRecognizer *tapleftview = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(leftviewclick:)];
    tapleftview.numberOfTapsRequired = 1;
    tapleftview.numberOfTouchesRequired = 1;
    [self.leftview addGestureRecognizer:tapleftview];
    
    UIPanGestureRecognizer *tappingleftview = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(tappingleftview:)];
    tappingleftview.maximumNumberOfTouches = 1;
    tappingleftview.minimumNumberOfTouches = 1;
    [self.leftview addGestureRecognizer:tappingleftview];
    
    UITapGestureRecognizer *taprightview = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(rightviewclick:)];
    taprightview.numberOfTapsRequired = 1;
    taprightview.numberOfTouchesRequired = 1;
    [self.rightview addGestureRecognizer:taprightview];
    
    UIPanGestureRecognizer *tappingrightview = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(tappingrightview:)];
    tappingrightview.maximumNumberOfTouches = 1;
    tappingrightview.minimumNumberOfTouches = 1;
    [self.rightview addGestureRecognizer:tappingrightview];
    
    //    view
    self.controlAV = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.layer.bounds.size.width - 30, self.view.layer.bounds.size.height, 30)];
    self.controlAV.alpha = 0.0;
    [self.view addSubview:self.controlAV];
    
    
    //    开始暂停
    self.startstop = [UIButton buttonWithType:UIButtonTypeSystem];
    self.startstop.frame = CGRectMake(10, self.controlAV.bounds.size.height - 30, 30, 30);
    if (self.startstopnum != 1) {
        [self.startstop setImage:[[UIImage imageNamed:@"zanting"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    } else if (self.startstopnum == 1) {
        [self.startstop setImage:[[UIImage imageNamed:@"kaishi"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    }
    
    [self.startstop addTarget:self action:@selector(stopAV:) forControlEvents:UIControlEventTouchDown];
    [self.controlAV addSubview:self.startstop];
    
    UIView *sliderbj = [[UIView alloc] initWithFrame:CGRectMake(47, self.controlAV.bounds.size.height - 16, self.controlAV.bounds.size.width - 174, 2)];
    sliderbj.backgroundColor = [UIColor grayColor];
    [self.controlAV addSubview:sliderbj];
    self.huancun = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 2)];
    self.huancun.backgroundColor = [UIColor colorWithRed:30 / 255.0 green:130 / 255.0 blue:110 / 255.0 alpha:1.0];
    [sliderbj addSubview:self.huancun];
    
    //    进度条
    self.jindu = [[UISlider alloc] initWithFrame:CGRectMake(45, self.controlAV.bounds.size.height - 30, self.controlAV.bounds.size.width - 170, 30)];
    self.jindu.maximumValue = self.howLong;
    self.jindu.minimumValue = 0.0f;
    self.jindu.value = self.now;
    self.jindu.minimumTrackTintColor = [UIColor colorWithRed:30 / 255.0 green:195 / 255.0 blue:153 / 255.0 alpha:1.0];
    self.jindu.maximumTrackTintColor = [UIColor clearColor];
    [self.jindu setThumbImage:[UIImage imageNamed:@"huakuai"] forState:UIControlStateNormal];
    [self.jindu addTarget:self action:@selector(jindubegin:) forControlEvents:UIControlEventTouchDown];
    [self.jindu addTarget:self action:@selector(jindu:) forControlEvents:UIControlEventValueChanged];
    [self.jindu addTarget:self action:@selector(jinduend:) forControlEvents:UIControlEventTouchUpInside];
    [self.controlAV addSubview:self.jindu];
    //    1.点击
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(jindutapclick:)];
    //    执行方法需要点击几次
    tap.numberOfTapsRequired = 1;
    //    几个手指
    tap.numberOfTouchesRequired = 1;
    [self.jindu addGestureRecognizer:tap];
    //    时间
    self.times = [[UILabel alloc] initWithFrame:CGRectMake(self.controlAV.bounds.size.width - 120, self.controlAV.bounds.size.height - 30, 80, 30)];
    self.times.font = [UIFont systemFontOfSize:13];
    self.times.textColor = [UIColor whiteColor];
    [self.controlAV addSubview:self.times];
    
    
    
    //    全屏按钮
    self.fullScreen = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.fullScreen setImage:[[UIImage imageNamed:@"suoxiao"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    self.fullScreen.frame = CGRectMake(self.controlAV.bounds.size.width - 35, self.controlAV.bounds.size.height - 30, 30, 30);
    [self.fullScreen addTarget:self action:@selector(fullScreen:) forControlEvents:UIControlEventTouchDown];
    [self.controlAV addSubview:self.fullScreen];
}
-(void)timers {
    NSInteger num = CMTimeGetSeconds(self.player.currentItem.currentTime) / CMTimeGetSeconds(self.player.currentItem.duration) * self.howLong;
    NSInteger fens = self.jindu.value / 60;
    NSInteger miaos = self.jindu.value - fens * 60;
    self.fen = self.howLong / 60;
    self.miao = self.howLong - self.fen * 60;
    self.times.text = [NSString stringWithFormat:@"%02ld:%02ld/%02ld:%02ld",fens, miaos, self.fen, self.miao];
    
    self.jindu.value = num;
    if (self.full == 0) {
        if (self.startstopnum != 1) {
            [self.player play];
        } else if (self.startstopnum == 1) {
            [self.player pause];
        }
    }
    
    NSTimeInterval timeInterval = [self availableDuration];// 计算缓冲进度
    if ((self.controlAV.bounds.size.width - 174) / self.howLong * timeInterval > 0) {
        self.huancun.frame = CGRectMake(0, 0, (self.controlAV.bounds.size.width - 174) / self.howLong * timeInterval, 2);
    }
    
    
    if (self.secondsAV > 0) {
        self.secondsAV -= 1;
        if (self.secondsAV == 1) {
            self.controlAV.alpha = 0.0;
            self.topview.alpha = 0.0;
            self.yinliang.hidden = YES;
            self.liangdula.hidden = YES;
        }
    }
}
//全屏键
-(void)fullScreen:(UIButton *)sender {
    self.full = 1;
    [self.timer invalidate];
    [self.player pause];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    [self.delegate jindunow:self.jindu.value withIfStart:self.startstopnum];
    //    [self.playerLayer removeFromSuperlayer];
    //    [self.fullScreen removeFromSuperview];
    //    [self.times removeFromSuperview];
    //    [self.jindu removeFromSuperview];
    //    [self.startstop removeFromSuperview];
    //    [self.controlAV removeFromSuperview];
    //    [self.playerLayer autorelease];
}
//暂停键
-(void)stopAV:(UIButton *)sender {
    //    ！= 1 播放状态  = 1 暂停状态
    if (self.startstopnum != 1) {
        [self.player pause];
        self.startstopnum = 1;
        // 暂停之后改变图片
        [self.startstop setImage:[[UIImage imageNamed:@"kaishi"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    } else if (self.startstopnum == 1) {
        [self.player play];
        self.startstopnum = 0;
        [self.startstop setImage:[[UIImage imageNamed:@"zanting"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    }
    //    控制台显示持续时间赋值
    self.secondsAV = 5;
}
//按下停止
- (void)jindubegin:(UISlider *)sender {
    [self.player pause];
    [self.timer setFireDate:[NSDate distantFuture]];
    self.secondsAV = 6;
}
//滑动
- (void)jindu:(UISlider *)sender {
    NSInteger fens = self.jindu.value / 60;
    NSInteger miaos = self.jindu.value - fens * 60;
    self.times.text = [NSString stringWithFormat:@"%02ld:%02ld/%02ld:%02ld",fens, miaos, self.fen, self.miao];
}
//松手开始
- (void)jinduend:(UISlider *)sender {
    CMTime dragedCMTime = CMTimeMake(self.jindu.value, 1);
    [_player seekToTime:dragedCMTime completionHandler:
     ^(BOOL finish){
         [self.timer setFireDate:[NSDate distantPast]];
         [self.player play];
     }];
    [self.timer setFireDate:[NSDate distantPast]];
    
}
//滑块点击事件
-(void)jindutapclick:(UITapGestureRecognizer *)sender {
    CGPoint point = [sender locationInView:self.jindu];
    NSInteger avlong = self.howLong;
    NSInteger width = self.controlAV.bounds.size.width - 170;
    self.jindu.value = point.x * ((float)avlong / (float)(width));
    CMTime dragedCMTime = CMTimeMake(self.jindu.value, 1);
    [self.player seekToTime:dragedCMTime];
    NSInteger fens = self.jindu.value / 60;
    NSInteger miaos = self.jindu.value - fens * 60;
    self.times.text = [NSString stringWithFormat:@"%02ld:%02ld/%02ld:%02ld",fens, miaos, self.fen, self.miao];
}
//音量点击
-(void)leftviewclick:(UITapGestureRecognizer *)sender {
    self.controlAV.alpha = 1.0;
    self.topview.alpha = 1.0;
    self.secondsAV = 6;
    CGPoint point = [sender locationInView:self.leftview];
    self.soundone = point.y;
}
//音量平移
-(void)tappingleftview:(UIPanGestureRecognizer *)sender {
    CGPoint point = [sender translationInView:self.leftview];
    self.player.volume = self.player.volume - (float)point.y / (float)2000;
    if (self.player.volume > 1) {
        self.player.volume = 1;
    } else if (self.player.volume < 0) {
        self.player.volume = 0;
    }
    self.yinliang.hidden = NO;
    self.yinliang.text = [NSString stringWithFormat:@"音量:%0.2f％", self.player.volume * 100];
    self.secondsAV = 6;
}
//亮度点击
-(void)rightviewclick:(UITapGestureRecognizer *)sender {
    self.controlAV.alpha = 1.0;
    self.topview.alpha = 1.0;
    self.secondsAV = 6;
}
//亮度平移
-(void)tappingrightview:(UIPanGestureRecognizer *)sender {
    CGPoint point = [sender translationInView:self.leftview];
    self.liangdu.alpha = self.liangdu.alpha + (float)point.y / (float)4000;
    if (self.liangdu.alpha > 0.5) {
        self.liangdu.alpha = 0.5;
    } else if (self.liangdu.alpha < 0) {
        self.liangdu.alpha = 0;
    }
    self.liangdula.hidden = NO;
    self.liangdula.text = [NSString stringWithFormat:@"亮度:%0.2f％", 100 - self.liangdu.alpha * 2 * 100];
    self.secondsAV = 6;
}

//横屏
- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    // 返回方向
    return (toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown);
}
- (long)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscapeRight;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
